package com.iwith.dongmoon.listadpater;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.iwith.dongmoon.activity.GroupListViewActivity;
import com.iwith.dongmoon.activity.R;
import com.iwith.dongmoon.gsonlist.BoardListItem;
import com.iwith.dongmoon.util.ImageDownloader;
import com.iwith.dongmoon.util.ImageDownloader.Mode;

public class IconGridAdapter extends ArrayAdapter<BoardListItem> {
	private Context mContext;
	private ArrayList<BoardListItem> items;
	private LayoutInflater mInflater;
	private ImageDownloader mImageDownloader;
	
	public IconGridAdapter(Context context, int textViewResourceId,	ArrayList<BoardListItem> list) {
		super(context, textViewResourceId, list);
		// TODO Auto-generated constructor stub

		this.mContext = context;
		this.items = list;
		this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.mImageDownloader = new ImageDownloader();
		this.mImageDownloader.setMode(Mode.CORRECT);
	}
	
	class ViewHolder {
		ImageView iconImage;
		TextView groupName;
	}

	@Override
	public BoardListItem getItem(int position) {
		if(items==null) 	return null;
		else 				return items.get(position);
	}
	
	@Override
	public int getCount(){
		if(items==null)		return 0;
		else				return super.getCount();
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.griditem_icon, null);
			holder.iconImage = (ImageView) convertView.findViewById(R.id.griditemicon_iconimage);
			holder.groupName = (TextView) convertView.findViewById(R.id.griditemicon_groupname);
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		final BoardListItem item = items.get(position);

		if (item != null) {
			if(item.getCa_icon()!=null){
				mImageDownloader.download(item.getCa_icon(), holder.iconImage);
			}
			holder.groupName.setText(item.getCa_name());
		}
		
		convertView.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, GroupListViewActivity.class);
				intent.putExtra("ca_name", item.getCa_name());
				mContext.startActivity(intent);
			}
		});

		return convertView;
	}
}
